<template>
    <div class="reference-data">
        <a-drawer :visible="isShowDrawer" :footer="false" :width="900" title-align="start" :header="false"
            :render-to-body="false" unmountOnClose>
            <div class="drawer-container">
                <div class="drawer-title">
                    <custom-title title="任务参考数据" />
                    <IconClose style="cursor: pointer; color: #86909c" size="20" @click="handelCloseDrawer" />
                </div>
                <div class="drawer-body">
                    <div class="drawer-body__task-list">
                        <div class="full-content">
                            <div class="add-reference">
                                <select-search placeholder="请输入任务名称" select-placeholder="请输入任务名称"
                                    :requestApi="searchTaskName" :config="searchFormConfig"
                                    :params="{ taskSettingId: props.taskSettingId }"
                                    @clear-selected="handelClearSelected" @change-select="changeSearchForm" />
                                <a-button type="primary" :disabled="!selectedTask.referenceTaskSettingId"
                                    @click="addReferTask">
                                    <template #icon>
                                        <icon-plus />
                                    </template>
                                    <template #default>添加参考任务</template>
                                </a-button>
                            </div>
                            <div class="add-tips">完成该任务时，可能需要查看某个任务的字段信息，用于参考，可在此编辑</div>
                        </div>
                        <div class="task-list">
                            <template v-if="referTaskList.length">
                                <div v-for="(item, index) in referTaskList" :key="item.referenceTaskSettingId"
                                    :class="['task-item', index === currentReferTaskIndex ? 'task-item--active' : '']">
                                    <div class="task-item__name" @click="handleReferTaskItem(item, index)">{{
                                        item.taskName }}</div>
                                    <div class="task-item__del" @click="deleteReferTask(index)">
                                        <!--                    <icon-delete size="16" />-->
                                        <GiSvgIcon name="org-del" size="16" />
                                    </div>
                                </div>
                            </template>
                            <a-empty v-else />
                        </div>
                        <div class="footer-buttons">
                            <a-button @click="handelCloseDrawer" class="cancel-button">取消</a-button>
                            <a-button type="primary" @click="handelConfirmDrawer"
                                :disabled="!referTaskList.length">确认</a-button>
                        </div>
                    </div>
                    <!--start 参考表单-->
                    <div class="drawer-body__form" v-spin-loading="isLoadingForm">
                        <div class="form-list" v-if="formItemsData.length">
                            <FormRender v-if="!isLoadingForm" ref="formRenderRef" mode="DESIGN" :forms="formItemsData"
                                :config="formConfigData" v-model="formModelData" />
                        </div>
                        <a-empty v-else />
                    </div>
                    <!--end 参考表单-->
                </div>
            </div>
        </a-drawer>
    </div>
</template>
<script setup lang="ts">
import { ref } from "vue";
import { Message } from "@arco-design/web-vue";
import { debounce } from "lodash";
import FormRender from "@/components/customComponents/formRender.vue";
import { searchTaskName, addReferenceData, previewTaskForm, referenceList } from "@/apis/system/referenceData";
import type { TaskNameItem } from "@/apis/system/referenceData/types";
import { parseOrDefault } from "@/utils";


const props = defineProps({
    taskSettingId: {
        required: true,
        type: String,
        default: ""
    }
});

const $emit = defineEmits(["handleReferenceClose"]);

const isShowDrawer = ref(true);

/**
 * 参考任务数据
 */
const getPreviewFormsList = async () => {
    const { data } = await referenceList(props.taskSettingId);
    referTaskList.value = data || [];
};
getPreviewFormsList();

/**
 * 搜索
 */
const selectedTask = ref<TaskNameItem>({ referenceTaskSettingId: "", referenceSettingId: "", taskName: "" });
const searchFormConfig = {
    label: "taskName",
    value: "referenceTaskSettingId",
    keyword: "taskName"
};
const defaultSelectFormList = ref([]) as any;
const changeSearchForm = (obj: any) => {
    console.log("搜索返回的值", obj);
    selectedTask.value = obj;
};
const handelClearSelected = () => {
    selectedTask.value = { referenceTaskSettingId: 0, referenceSettingId: 0, taskName: "" };
    defaultSelectFormList.value = [];
};

/**
 * 参考任务列表
 */
const isLoadingForm = ref(false);
const referTaskList = ref<TaskNameItem[]>([]);
const currentReferTaskIndex = ref(-1);
const formItemsData = ref([]);
const formConfigData = ref({});
const formModelData = ref({});
const getPreviewTaskForm = async (referenceTaskSettingId: number | string) => {
    try {
        isLoadingForm.value = true;
        const { data } = await previewTaskForm(referenceTaskSettingId);
        const formItems = parseOrDefault(data.formItems, []);
        formItems.forEach((item: any) => {
            item.props.disabled = true;
        });
        formItemsData.value = formItems;
        isLoadingForm.value = false;
    } catch (err) {
        isLoadingForm.value = false;
        console.log(err);
    }
};
const handleReferTaskItem = async (item: TaskNameItem, index: number) => {
    currentReferTaskIndex.value = index;
    getPreviewTaskForm(item.referenceTaskSettingId);
};
const deleteReferTask = (index: number) => {
    let currenIndex = index > 0 ? index - 1 : 0;
    referTaskList.value.splice(index, 1);
    formItemsData.value = [];
    if (referTaskList.value.length) {
        currentReferTaskIndex.value = currenIndex;
        const referenceTaskSettingId = referTaskList.value[currenIndex].referenceTaskSettingId;
        getPreviewTaskForm(referenceTaskSettingId);
    }
};
const addReferTask = () => {
    if (referTaskList.value.length >= 5) {
        return Message.error("最多添加5个参考任务");
    }
    const isHaveData = referTaskList.value.find(
        (item: TaskNameItem) => item.referenceTaskSettingId === selectedTask.value.referenceTaskSettingId
    );
    if (isHaveData) {
        Message.error("您已选择过该数据,不能重复选择");
        return;
    }
    referTaskList.value.push(selectedTask.value);
    currentReferTaskIndex.value = referTaskList.value.length - 1;
    getPreviewTaskForm(selectedTask.value.referenceTaskSettingId);
};

/**
 * 取消
 */
const handelCloseDrawer = () => {
    isShowDrawer.value = false;
    selectedTask.value = { referenceTaskSettingId: 0, referenceSettingId: 0, taskName: "" };
    referTaskList.value = [];
    formConfigData.value = [];
    $emit("handleReferenceClose");
};
/**
 * 确定
 */
const submitReferenceData = async () => {
    try {
        const postData =
            referTaskList.value?.map(item => {
                return {
                    taskSettingId: props.taskSettingId,
                    referenceTaskSettingId: item.referenceTaskSettingId
                };
            }) || [];
        await addReferenceData(props.taskSettingId, postData);
        handelCloseDrawer();
        Message.success("添加成功");
    } catch (err) {
        console.log("submitReferenceData>>>", err);
    }
};
const handelConfirmDrawer = debounce(submitReferenceData, 500);
</script>

<style scoped lang="scss">
.reference-data {
    :deep(.arco-drawer-body) {
        padding: 0;
    }

    .drawer-container {
        .drawer-title {
            @include flex-align;
            justify-content: space-between;
            padding: 15px;
            border-bottom: 1px solid #dcdfe6;
        }

        .drawer-body {
            @include flex;

            &__task-list {
                @include flex-column;
                padding: 15px;
                width: 490px;
                height: calc(100vh - 95px);
                border-right: 1px solid #dcdfe6;

                .add-reference {
                    @include flex;
                }

                .task-list {
                    position: relative;
                    flex-grow: 1;
                    overflow: auto;

                    .task-item {
                        @include flex-align;
                        margin-bottom: 10px;
                        cursor: pointer;

                        &__name {
                            width: 90%;
                            padding: 5px 12px;
                            border: 1px solid #e1e6ed;
                            font-size: 14px;
                            color: #3d3d3d;
                        }

                        &__del {
                            width: 10%;
                            text-align: center;
                            color: #606266;
                        }

                        &--active .task-item__name {
                            color: #007dff;
                            border: 1px solid #007dff;
                        }
                    }
                }

                .footer-buttons {
                    @include flex-center;
                    flex-shrink: 0; //保持内容不缩放，适用于内容不确定大小时候

                    button {
                        width: 120px;
                        height: 36px;
                    }

                    button:nth-of-type(1) {
                        background: #f2f3f5;
                        border: 0;
                        margin-right: 16px;
                    }
                }

                .add-tips {
                    font-size: 12px;
                    color: #86909c;
                    margin: 20px 0 10px 0;
                }
            }

            &__form {
                position: relative;
                width: 410px;
                padding: 15px;
            }
        }
    }

    :deep(.arco-empty) {
        @include position-center;
    }

    :deep(.arco-select-view-single) {
        border: 0;
        border-radius: 2px;
    }
}
</style>